<template>
  <div>
    <div class="app-container">
      <h-table-list
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="device_patrol_items.records"
        :columns="columns"
        :pagination-info="paginationInfo"
        :form-options="formOptions"
        @size-change="handleSizeChange"
      >
        <ListOpearteButton />
        <template slot="userType" slot-scope="scope">
          <p>
            <i
              v-if="scope.row.userType == 0"
              class="iconfont deviceicon-dian-0"
            >PC</i>
            <i
              v-if="scope.row.userType == 1"
              class="iconfont deviceicon-dian-1"
            >手机</i>
          </p>
        </template>
        <!-- <template slot="createTime" slot-scope="scope">
          <p>
           {{scope.row.createdTime}}
          </p>
        </template> -->
        <template slot="enable" slot-scope="scope">
          <p>
            <i
              v-if="scope.row.userType == 0"
              class="iconfont deviceicon-dian-0"
            >停用</i>
            <i
              v-if="scope.row.userType == 1"
              class="iconfont deviceicon-dian-1"
            >启用</i>
          </p>
        </template>
        <template slot="operate-column" slot-scope="scope">
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify
      :visible.sync="dialogFormVisible"
      title="巡检项"
      @cancel="cancel"
      @update="dialogSubmit"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="巡检部位" prop="part">
          <el-input v-model="ruleForm.part" />
        </el-form-item>
        <el-form-item label="巡检内容" prop="content">
          <el-input v-model="ruleForm.content" />
        </el-form-item>
        <el-form-item label="巡检基准" prop="standard">
          <el-input v-model="ruleForm.standard" />
        </el-form-item>
        <el-form-item label="巡检方法" prop="method">
          <el-input v-model="ruleForm.method" />
        </el-form-item>
        <el-form-item label="上传图片" prop="upPicFlag">
          <el-select v-model="ruleForm.upPicFlag">
            <el-option :value="0" :label="'不上传'" />
            <el-option :value="1" :label="'选填'" />
            <el-option :value="2" :label="'必填'" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传视频" prop="upVideoFlag">
          <el-select v-model="ruleForm.upVideoFlag">
            <el-option :value="0" :label="'不上传'" />
            <el-option :value="1" :label="'选填'" />
            <el-option :value="2" :label="'必填'" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="itemGroupId">
          <el-select v-model="ruleForm.itemGroupId">
            <el-option
              v-for="e in groupsOptions"
              :key="e.itemGroupId ||e"
              :label="e.groupName ||e"
              :value="e.itemGroupId||e"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import waves from '@/directive/waves' // waves directive
import DownloadIdentify from '@/components/FormDialog'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ListOpearteButton from '@/components/AllButton/button2'
import tableButton from '@/components/AllButton/button3'
import data from './const'

export default {
  name: 'DevicePatrolItems',
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      groupsOptions: [],
      dialogFormVisible: false,
      loadList: false,
      ruleForm: {
        part: '',
        content: '',
        itemGroupId: '',
        standard: '',
        method: '',
        upPicFlag: '',
        upVideoFlag: ''
      },
      rules: {
        part: [
          { required: true, message: '请填写巡检部位', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写巡检内容', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        upPicFlag: [{ required: true, trigger: 'blur' }],
        upVideoFlag: [{ required: true, trigger: 'blur' }],
        itemGroupId: [{ required: true, trigger: 'blur' }]
      },

      paginationInfo: {
        sizeChange: e => {
          console.log(e)
        },
        currentChange: e => {
          this.$store.dispatch('device_patrol_items/setListSearchParams', {
            current: e
          })
          this.getList(
            Object.assign(
              {},
              this.$store.state.device_patrol_items.listSearchParams
            )
          )
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: '查询',
        showResetBtn: true,
        searchParamsHandler: () => {
          console.log('搜索')
          this.getList(
            this.$store.state.device_patrol_items.listSearchParams
          )
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params)
          this.$store.dispatch(
            'device_patrol_items/setListSearchParams',
            params
          )
        },
        resetBtnCallback: () => {
          this.$store.dispatch(
            'device_patrol_items/setListSearchParams',
            {}
          )
          this.getList()
        },
        forms: [
          { prop: 'itemGroupId', label: '分组', itemType: 'select', options: [] },

          { prop: 'part', label: '巡检部位' },
          { prop: 'content', label: '巡检内容' }
          // {
          //   prop: "useDepartmentId",
          //   label: "归属部门",
          //   itemType: "select",
          //   options: [
          //     { value: "", label: "部门1" },
          //     { value: 0, label: "部门2" },
          //     { value: 1, label: "部门3" },
          //   ],
          // },

          // {
          //   prop: "positionsId",
          //   label: "职位",
          //   itemType: "select",
          //   options: [
          //     { value: 0, label: "通用" },
          //     { value: 1, label: "专用" },
          //   ],
          // },
          //  {
          //   prop: "userType",
          //   label: "账号类别",
          //   itemType: "select",
          //   options: [
          //     { value: "0", label: "手机" },
          //     { value: "1", label: "PC" },
          //   ],
          // },
        ]
      },
      columns: [
        { prop: 'itemGName', label: '分组' },

        {
          prop: 'part',
          label: '巡检部位',
          width: 100
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: 'content',
          label: '巡检内容',
          width: 100
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.content ? deviceInfo.content :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: 'standard', label: '巡检基准', minWidth: 180 },
        { prop: 'method', label: '巡检方法', minWidth: 180 },
        // {
        //   prop: "itemsSum",
        //   label: "巡检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        {
          prop: 'upPicFlag',
          label: '上传图片',
          minWidth: 180,
          filter: 'formatIsNecessary'
        },
        {
          prop: 'upVideoFlag',
          label: '上传视频',
          minWidth: 180,
          filter: 'formatIsNecessary'
        },
        // {
        //   prop: "createdTime",
        //   label: "创建时间",
        //   minWidth: 180,
        // //  slotName: "createdTime",
        // },
        {
          prop: 'operate',
          label: '操作',
          minWidth: 240,
          slotName: 'operate-column',
          fixed: 'right'
        }
      ],
      tableData: []
    }
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(['device_patrol_items', 'app'])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop
      const data = this.$store.state.device_patrol_items.listSearchParams
      e.defaultValue = data[key] || ''
      return e
    })),
    // this.submitHandler=this.searchWithParams
    this.$store
      .dispatch(this.$store_url_button, {
        add: this.add,
        export: this.export,
        delete: this.delete,
        edit: this.edit,
        detail: this.detail,
        using: this.using,
        useless: this.useless,
        downloadTemplete: this.downloadTemplete,
        downloadIdentify: this.downloadIdentify
      })
      .then(async() => {
        // await this.$store.dispatch("app/getCodeList", []); //code转码
        this.getList() // 表格数据
        this.getGroupItemsList()// 分组查询
      })

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    // 查询巡检项分组
    getGroupItemsList() {
      this.$store.dispatch('device_patrol_itemsGroup/getItemsGroupList').then(res => {
        const { data } = res
        const itemGropusData = data.map(e => {
          return { label: e.groupName, value: e.itemGroupId }
        })
        this.$set(this.formOptions.forms[0], 'options', itemGropusData)
      })
    },
    cancel() {
      this.dialogFormVisible = false
    },
    dialogSubmit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.$store
            .dispatch('device_patrol_items/saveInfo', this.ruleForm)
            .then(res => {
              this.getList()
              this.dialogFormVisible = false
            })
            .catch(err => {})
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 自定义该业务模块下的按钮方法
    // 自定义该业务模块下的按钮方法
    using(row) {
      this.$store
        .dispatch('device_patrol_items/useUserInfo', row.id)
        .then(res => {
          this.getList()
          // this.dialogFormVisible=false
        })
        .catch(err => {})
    },
    useless(row) {
      this.$store
        .dispatch('device_patrol_items/uselessUserInfo', row.id)
        .then(res => {
          this.getList()
          // this.dialogFormVisible=false
        })
        .catch(err => {})
    },
    async add(row) {
      console.log(row)
      const data = await this.$store.dispatch('device_patrol_itemsGroup/requestDeviceList')

      this.ruleForm = {
        part: '',
        content: '',
        itemGroupId: '',
        standard: '',
        method: '',
        upPicFlag: '',
        upVideoFlag: ''
      }
      const options = []
      this.$store.state.device_patrol_itemsGroup.records.map(e => {
        options.push({
          itemGroupId: e.itemGroupId,
          groupName: e.groupName
        })
      })

      this.$set(this, 'groupsOptions', options)
      this.dialogFormVisible = true
    },
    edit(row) {
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
    },
    downloadIdentify(row) {
      console.log('下载设备标识卡')
      this.dialogFormVisible = true
    },
    async downloadTemplete(ids) {
      console.log('下载导出模板')
      const download = await this.$store.dispatch(
        'device_patrol_items/downloadTemplete'
      )
      window.open(download.data)
      console.log(download)
    },
    delete(row) {
      console.log(row)
      this.$confirm(
        `巡检项删除后不可恢复，确认删除？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store
            .dispatch('device_patrol_items/deleteDeviceInfo', row.id)
            .then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '删除失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    update() {},
    detail(row) {
      console.log(row)

      localStorage.setItem('/device-basic/component/detail/index', row.id)
      this.$router.push('/device-basic/component/detail/index')
    },
    import() {},
    export() {
      console.log('导出')
      this.$store.dispatch('device_patrol_items/exportFile')
    },
    // 弹窗的关闭
    cancel() {
      console.log('关闭弹窗')
      this.dialogFormVisible = false
    },
    // 更新弹窗数据
    updateDialog() {
      console.log('更新并关闭弹窗')
      this.dialogFormVisible = false
    },
    // 搜索按钮
    searchWithParams() {
      console.log('搜索')
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args)
      await this.$store.dispatch(
        'device_patrol_items/requestDeviceList',
        args
      )
      this.paginationInfo.total = this.$store.state.device_patrol_items.total
    },
    handleFilter(args) {
      this.listQuery.page = 1
      this.getList(args)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
